<template>
    <!-- 右侧预览区 -->
    <div
        class="flex-1 min-w-0 h-full bg-[#18191c] text-white relative z-0 select-none flex flex-col items-start px-8 py-4 overflow-auto"
        @scroll="handleScroll">
        <!-- 顶部Tab筛选栏 -->
        <div class="flex gap-2 border border-[#232428] bg-[#18191c] rounded-md mb-8">
            <button v-for="tab in tabs" :key="tab.value" @click="taskType = tab.value" :class="[
                'px-5 h-8 rounded-md text-sm font-bold transition-all',
                taskType === tab.value
                    ? 'bg-[#232428] text-white shadow'
                    : 'bg-transparent text-[#bfc0c2] hover:bg-[#232428]/60'
            ]">
                {{ tab.label }}
            </button>
        </div>
        <!-- 固定右侧全局缩略图区 -->
        <div class="fixed top-32 right-12 flex flex-col gap-2 z-50">
            <div v-for="(item, idx) in filteredVideoList" :key="item.video_id" @click="scrollToCard(idx)" :class="[
                'w-[72px] h-[72px] rounded-md overflow-hidden border-2 cursor-pointer transition-all duration-150',
                activeIndex === idx
                    ? 'border-[#7fff00] shadow-[0_0_0_2px_#7fff00]'
                    : 'border-[#232428] hover:border-[#bfc0c2]'
            ]" style="box-shadow: 0 2px 8px 0 rgba(0,0,0,0.10);">
                <video v-if="isVideoType(item.task_type) && item.oss_result" :src="item.oss_result" class="w-full h-full object-cover" />
                <img v-else-if="item.oss_result" :src="item.oss_result" class="w-full h-full object-cover" />
            </div>
        </div>
        <!-- 多条内容区 -->
        <div class="flex flex-col gap-8 w-full">
            <div v-for="(item, idx) in filteredVideoList" :key="item.video_id" :ref="'card-' + idx"
                class="flex flex-col w-full">
                <!-- 标题栏 -->
                <div class="flex items-center gap-2 mb-2">
                    <icon-park-magic theme="outline" size="20" fill="#7fff00" />
                    <span class="text-lg font-bold text-white">{{ getTaskTypeText(item.task_type) }}</span>
                    <span class="mx-2 text-[#232428]">|</span>
                    <span class="text-sm text-[#bfc0c2]">{{ formatTime(item.create_time) }}</span>
                    <span class="mx-2 text-[#232428]">|</span>
                    <span :class="[
                        'text-sm font-bold',
                        item.task_status === 1 ? 'text-[#7fff00]' : 
                        item.task_status === 2 ? 'text-[#7fff00]' : 
                        'text-red-500'
                    ]">
                        {{ getTaskStatusText(item.task_status) }}
                    </span>
                </div>
                <div
                    class="flex flex-row bg-[#232428] justify-center rounded-md shadow-lg overflow-hidden relative w-full max-w-[93%]">
                    <div class="flex flex-col items-center justify-center relative" style="width: 420px;">
                        <!-- 编辑按钮 -->
                        <button v-if="item.task_status === 2"
                            class="absolute top-4 right-4 w-8 h-8 flex items-center justify-center rounded-full bg-[#232428] shadow hover:bg-[#2e2f33] transition">
                            <icon-park-edit theme="outline" size="18" fill="#bfc0c2" />
                        </button>
                        <!-- 视频/图片展示 -->
                        <template v-if="item.task_status === 2">
                            <!-- 视频展示 -->
                            <video v-if="isVideoType(item.task_type)"
                                :src="item.oss_result"
                                class="h-[480px] w-[340px] object-cover bg-[#18191c] border border-[#232428]"
                                controls
                                preload="metadata">
                            </video>
                            <!-- 图片展示 -->
                            <img v-else
                                :src="item.oss_result"
                                class="h-[480px] w-[340px] object-cover bg-[#18191c] border border-[#232428]" />
                        </template>
                        <!-- 生成中状态 -->
                        <div v-else-if="item.task_status === 1"
                            class="flex items-center justify-center w-[340px] h-[480px] bg-[#18191c] border border-[#232428]">
                            <span class="text-[#bfc0c2]">Generating...</span>
                        </div>
                        <!-- 失败状态 -->
                        <div v-else
                            class="flex items-center justify-center w-[340px] h-[480px] bg-[#18191c] border border-[#232428]">
                            <span class="text-red-500">{{ item.task_msg || 'Generation Failed' }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 加载状态 -->
            <div v-if="loading" class="flex justify-center py-4">
                <span class="text-[#bfc0c2]">Loading...</span>
            </div>
            <!-- 无更多数据 -->
            <div v-if="!hasMore && videoList.length > 0" class="flex justify-center py-4">
                <span class="text-[#bfc0c2]">No more data</span>
            </div>
            <!-- 空状态 -->
            <div v-if="!loading && videoList.length === 0" class="flex justify-center py-4">
                <span class="text-[#bfc0c2]">No data</span>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { Effects, PictureOne, VideoTwo, ClothesCrewNeck, Switch, Close, AddPicture, Info } from '@icon-park/vue-next';
import { getVideoList } from '@/api';
import { Message } from '@arco-design/web-vue';

// 任务类型
type TaskType = 1 | 2 | 3 | 4;

// 任务状态类型
type TaskStatus = 1 | 2 | 3;

// 视频列表项类型
interface VideoListItem {
    task_type: TaskType;
    parameters: string;
    task_status: TaskStatus;
    task_msg: string;
    video_id: string;
    oss_result: string;
    create_time: number;
}

// 视频列表响应类型
interface VideoListResponse {
    total: number;
    page: number;
    pageSize: number;
    list: VideoListItem[];
}

export default defineComponent({
    name: 'Preview',
    components: {
        'icon-park-effects': Effects,
        'icon-park-picture': PictureOne,
        'icon-park-video': VideoTwo,
        'icon-park-clothes-crew-neck': ClothesCrewNeck,
        'icon-park-switch': Switch,
        'icon-park-close': Close,
        'icon-park-add-picture': AddPicture,
        'icon-park-info': Info
    },
    props: {
        visible: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            taskType: 0,
            videoList: [] as VideoListItem[],
            selectedPreviewIndex: 0,
            selectedTab: 0,
            showFavorite: false,
            tabs: [
                { label: 'All', value: 0 },
                { label: 'Image', value: 1 },
                { label: 'Video', value: 2 }
            ],
            activeIndex: 0,
            // 分页相关
            page: 1,
            pageSize: 10,
            total: 0,
            loading: false,
            hasMore: true
        }
    },
    computed: {
        filteredVideoList() {
            if (this.selectedTab === 0) {
                return this.videoList;
            } else if (this.selectedTab === 1) {
                return this.videoList.filter(item => this.showFavorite);
            } else if (this.selectedTab === 2) {
                return this.videoList.filter(item => item.task_status === 1);
            } else if (this.selectedTab === 3) {
                return this.videoList.filter(item => item.task_status === 2);
            }
            return this.videoList;
        }
    },
    methods: {
        async loadVideoList(reset = false) {
            if (this.loading || (!this.hasMore && !reset)) return;

            try {
                this.loading = true;
                if (reset) {
                    this.page = 1;
                    this.videoList = [];
                }

                const params = {
                    task_type: this.taskType,
                    page: this.page,
                    pageSize: this.pageSize
                };

                const response = await getVideoList(params);
                const data = response.data as VideoListResponse;

                if (reset) {
                    this.videoList = data.list;
                } else {
                    this.videoList = [...this.videoList, ...data.list];
                }

                this.total = data.total;
                this.hasMore = this.videoList.length < data.total;
                this.page++;

            } catch (error) {
                console.error('Load video list error:', error);
                Message.error('加载视频列表失败');
            } finally {
                this.loading = false;
            }
        },

        handleScroll(e: Event) {
            const target = e.target as HTMLElement;
            const { scrollTop, scrollHeight, clientHeight } = target;
            
            // 滚动到底部时加载更多
            if (scrollHeight - scrollTop - clientHeight < 50) {
                this.loadVideoList();
            }
        },

        scrollToCard(index: number) {
            this.activeIndex = index;
            this.$nextTick(() => {
                const card = this.$refs[`card-${index}`];
                if (Array.isArray(card) && card.length > 0 && card[0] instanceof HTMLElement) {
                    (card[0] as HTMLElement).scrollIntoView({ behavior: 'smooth', block: 'center' });
                } else if (card && (card as HTMLElement).scrollIntoView) {
                    (card as HTMLElement).scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
            });
        },

        // 格式化时间戳
        formatTime(timestamp: number): string {
            const date = new Date(timestamp); // 直接使用毫秒时间戳
            return date.toLocaleString('en-US', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            });
        },

        // 获取任务状态文本
        getTaskStatusText(status: TaskStatus): string {
            const statusMap: Record<TaskStatus, string> = {
                1: 'Generating',
                2: 'Completed',
                3: 'Failed'
            };
            return statusMap[status];
        },

        // 获取任务类型文本
        getTaskTypeText(type: TaskType): string {
            const typeMap: Record<TaskType, string> = {
                1: 'Image to Image',
                2: 'Multi-image to Video',
                3: 'Single Image Effect Video',
                4: 'Multi-image Effect Video'
            };
            return typeMap[type];
        },

        // 判断是否为视频类型
        isVideoType(type: TaskType): boolean {
            return [2, 4 , 3].includes(type);
        }
    },
    watch: {
        selectedTab() {
            this.loadVideoList(true);
        },
        taskType() {
            this.loadVideoList(true);
        }
    },
    mounted() {
        document.body.setAttribute('arco-theme', 'dark');
        this.loadVideoList();
    }
});
</script>